using McpApi.Models;
using System.Collections.Concurrent;

namespace McpApi.Services
{
    /// <summary>
    /// MCP工具注册表实现
    /// </summary>
    public class ToolRegistry : IToolRegistry
    {
        private readonly ILogger<ToolRegistry> _logger;
        private readonly ConcurrentDictionary<string, Tool> _tools = new();
        private readonly ConcurrentDictionary<string, Func<Dictionary<string, object>, Task<MESToolResult>>> _handlers = new();

        public ToolRegistry(ILogger<ToolRegistry> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 获取所有可用工具
        /// </summary>
        public async Task<IEnumerable<Tool>> GetToolsAsync()
        {
            await Task.CompletedTask; // 保持异步接口一致性
            return _tools.Values.ToList();
        }

        /// <summary>
        /// 调用指定工具
        /// </summary>
        public async Task<MESToolResult> CallToolAsync(string toolName, Dictionary<string, object> arguments)
        {
            try
            {
                if (!_handlers.TryGetValue(toolName, out var handler))
                {
                    return new MESToolResult
                    {
                        Success = false,
                        Message = $"工具 '{toolName}' 未找到",
                        ErrorCode = "TOOL_NOT_FOUND"
                    };
                }

                _logger.LogInformation("执行工具: {ToolName}", toolName);
                var result = await handler(arguments);
                
                _logger.LogInformation("工具执行完成: {ToolName}, 成功: {Success}", toolName, result.Success);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "工具执行异常: {ToolName}", toolName);
                return new MESToolResult
                {
                    Success = false,
                    Message = $"工具执行异常: {ex.Message}",
                    ErrorCode = "EXECUTION_ERROR"
                };
            }
        }

        /// <summary>
        /// 注册工具
        /// </summary>
        public async Task RegisterToolAsync(Tool tool, Func<Dictionary<string, object>, Task<MESToolResult>> handler)
        {
            await Task.CompletedTask; // 保持异步接口一致性
            
            _tools.TryAdd(tool.Name, tool);
            _handlers.TryAdd(tool.Name, handler);
            
            _logger.LogInformation("注册工具: {ToolName} - {Description}", tool.Name, tool.Description);
        }

        /// <summary>
        /// 获取工具数量
        /// </summary>
        public int GetToolCount()
        {
            return _tools.Count;
        }
    }
}
